<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isView ? '查看降雨记录' : (formData?.id ? '编辑降雨记录' : '新增降雨记录')"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      :disabled="isView"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="监测站点" prop="stationId">
            <el-select
              v-model="form.stationId"
              placeholder="请选择监测站点"
              style="width: 100%"
            >
              <el-option
                v-for="station in rainfallStations"
                :key="station.id"
                :label="station.name"
                :value="station.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="降雨日期" prop="rainfallDate">
            <el-date-picker
              v-model="form.rainfallDate"
              type="date"
              placeholder="选择降雨日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-time-picker
              v-model="form.startTime"
              placeholder="选择开始时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-time-picker
              v-model="form.endTime"
              placeholder="选择结束时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="总降雨量(mm)" prop="totalRainfall">
            <el-input-number
              v-model="form.totalRainfall"
              :min="0"
              :precision="1"
              placeholder="请输入总降雨量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大强度(mm/h)" prop="maxIntensity">
            <el-input-number
              v-model="form.maxIntensity"
              :min="0"
              :precision="1"
              placeholder="请输入最大强度"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="降雨类型" prop="rainfallType">
            <el-select
              v-model="form.rainfallType"
              placeholder="请选择降雨类型"
              style="width: 100%"
            >
              <el-option label="小雨" value="小雨" />
              <el-option label="中雨" value="中雨" />
              <el-option label="大雨" value="大雨" />
              <el-option label="暴雨" value="暴雨" />
              <el-option label="大暴雨" value="大暴雨" />
              <el-option label="特大暴雨" value="特大暴雨" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="天气状况" prop="weatherCondition">
            <el-select
              v-model="form.weatherCondition"
              placeholder="请选择天气状况"
              style="width: 100%"
            >
              <el-option label="晴" value="晴" />
              <el-option label="多云" value="多云" />
              <el-option label="阴" value="阴" />
              <el-option label="小雨" value="小雨" />
              <el-option label="中雨" value="中雨" />
              <el-option label="大雨" value="大雨" />
              <el-option label="暴雨" value="暴雨" />
              <el-option label="雷阵雨" value="雷阵雨" />
              <el-option label="阴雨" value="阴雨" />
              <el-option label="多云转雨" value="多云转雨" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="是否典型" prop="isTypical">
            <el-radio-group v-model="form.isTypical">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="记录人" prop="recordPerson">
            <el-input
              v-model="form.recordPerson"
              placeholder="请输入记录人"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="form.phone"
              placeholder="请输入联系电话"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属部门" prop="department">
            <el-input
              v-model="form.department"
              placeholder="请输入所属部门"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="风向" prop="windDirection">
            <el-select
              v-model="form.windDirection"
              placeholder="请选择风向"
              style="width: 100%"
            >
              <el-option label="北风" value="北风" />
              <el-option label="东北风" value="东北风" />
              <el-option label="东风" value="东风" />
              <el-option label="东南风" value="东南风" />
              <el-option label="南风" value="南风" />
              <el-option label="西南风" value="西南风" />
              <el-option label="西风" value="西风" />
              <el-option label="西北风" value="西北风" />
              <el-option label="无风" value="无风" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="风速(m/s)" prop="windSpeed">
            <el-input-number
              v-model="form.windSpeed"
              :min="0"
              :precision="1"
              placeholder="请输入风速"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="气温(℃)" prop="temperature">
            <el-input-number
              v-model="form.temperature"
              :precision="1"
              placeholder="请输入气温"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="湿度(%)" prop="humidity">
            <el-input-number
              v-model="form.humidity"
              :min="0"
              :max="100"
              :precision="1"
              placeholder="请输入湿度"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          v-if="!isView"
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Props {
  visible: boolean
  formData?: any
  isView?: boolean
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  formData: null,
  isView: false
})

const emit = defineEmits<Emits>()

// 监测站点
const rainfallStations = ref([
  { id: 1, name: '西音水库主站' },
  { id: 2, name: '大坝监测站' },
  { id: 3, name: '库区中心站' },
  { id: 4, name: '入库口站' },
  { id: 5, name: '出库口站' },
  { id: 6, name: '上游监测站' },
  { id: 7, name: '下游监测站' }
])

const formRef = ref<FormInstance>()
const submitLoading = ref(false)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单数据
const form = reactive({
  id: null,
  stationId: '',
  rainfallDate: '',
  startTime: '',
  endTime: '',
  totalRainfall: null,
  maxIntensity: null,
  rainfallType: '',
  weatherCondition: '',
  isTypical: false,
  recordPerson: '',
  phone: '',
  department: '',
  windDirection: '',
  windSpeed: null,
  temperature: null,
  humidity: null,
  remark: ''
})

// 表单验证规则
const rules: FormRules = {
  stationId: [
    { required: true, message: '请选择监测站点', trigger: 'change' }
  ],
  rainfallDate: [
    { required: true, message: '请选择降雨日期', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  totalRainfall: [
    { required: true, message: '请输入总降雨量', trigger: 'blur' }
  ],
  maxIntensity: [
    { required: true, message: '请输入最大强度', trigger: 'blur' }
  ],
  rainfallType: [
    { required: true, message: '请选择降雨类型', trigger: 'change' }
  ],
  weatherCondition: [
    { required: true, message: '请选择天气状况', trigger: 'change' }
  ],
  recordPerson: [
    { required: true, message: '请输入记录人', trigger: 'blur' }
  ]
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    stationId: '',
    rainfallDate: '',
    startTime: '',
    endTime: '',
    totalRainfall: null,
    maxIntensity: null,
    rainfallType: '',
    weatherCondition: '',
    isTypical: false,
    recordPerson: '',
    phone: '',
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData) {
      Object.assign(form, newData)
    } else {
      resetForm()
    }
  },
  { immediate: true }
)

// 模拟API - 保存降雨记录
const saveRainfallRecord = async (data: any) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    return { success: true }
  } catch (error) {
    throw new Error('保存失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    // 计算持续时长
    if (form.startTime && form.endTime) {
      const start = new Date(`2000-01-01 ${form.startTime}`)
      const end = new Date(`2000-01-01 ${form.endTime}`)
      const duration = (end.getTime() - start.getTime()) / (1000 * 60 * 60)
      form.duration = Math.round(duration * 100) / 100
    }

    // 获取站点名称
    const station = rainfallStations.value.find(s => s.id === form.stationId)
    if (station) {
      form.stationName = station.name
    }

    await saveRainfallRecord(form)
    
    ElMessage.success(form.id ? '更新成功' : '新增成功')
    emit('success')
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消
const handleCancel = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>